package com.cxrj.zhsq.utils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

public class PictureUpload {
	public Map<String, Object> pictureUpload(HttpServletRequest request){
		//初始化通用multipart解析器  
		//解析请求，将文件信息放到迭代器里     
		Map<String,Object> resultMap = new HashMap<>();
		CommonsMultipartResolver  resolver = new CommonsMultipartResolver(request.getSession().getServletContext());
		resolver.setDefaultEncoding("utf-8");
		String  fileName = "";
		if(resolver.isMultipart(request)){
			MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest)request;  
			Map<String, MultipartFile> files = multipartRequest.getFileMap();//得到文件map对象  
			if(files.size()!=0){
				for(MultipartFile file :files.values()){  
					fileName=file.getOriginalFilename();//相片的名字  
					String lastUrl = request.getSession().getServletContext().getRealPath("/")+"../upload/enterprisePicture";
					File dir = new File(lastUrl);  
//							迭代文件，存放到某一路径里  
					if(!dir.exists()){
						dir.mkdirs();  
					}//目录不存在则创建  
					//数据库存的图片路径
					InputStream inputStream=null;
					String filePath=request.getSession().getServletContext().getRealPath("/")+"../upload/enterprisePicture"+File.separator+fileName;
					try {
						//上传图片
						inputStream=file.getInputStream();
						byte[] b = new byte[(int)file.getSize()];  
						int read = 0;  
						int i = 0;  
						while((read=inputStream.read())!=-1){  
							b[i] = (byte) read;  
							i++;  
						}  
						inputStream.close();  
						OutputStream os = new FileOutputStream(new File(filePath));
						os.write(b);  
						os.flush();  
						os.close(); 
					} catch (IOException e) {
						e.printStackTrace();
					}
				}  
			}
			resultMap.put("flag", resolver.isMultipart(request));
		}else{
			resultMap.put("flag", false);
		}
		return resultMap;
	}

}
